package com.kexin.jbsg;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.kexin.jbsg.util.APNUtil;
import com.kexin.jbsg.util.PhoneInfoUtil;
import com.kexin.jbsg.util.Util;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

/**
 * @author oven:
 * @version 创建时间：2013-6-18 下午4:27:03
 * 
 */
public abstract class AbstractUnityActivity extends UnityPlayerActivity implements OnClickListener,CreateOrderSuccessCallBack{
//public abstract class AbstractUnityActivity extends Activity implements OnClickListener,CreateOrderSuccessCallBack{
	public static final String key="komol";
	
	public static final String createOrderUrl = "http://112.25.14.70:8080/kom_login_cmg/CreatePayOrder";
	//public static final String createOrderUrl = "http://login.efgame.cn:8080/kom_payResponse_new/CreatePayOrder";
	public static final String createOrderUrlDebug = "http://116.255.235.123:8090/kom_payResponse_new/CreatePayOrder";
	
	public static final String LOGINURL = "http://112.25.14.70:8080/kom_login_cmg/KomLogin";
	//public static final String LOGINURL = "http://login.efgame.cn:8080/kom_login_new/KomLogin";
	public static final String LOGINURL_DEBUG = "http://116.255.235.123:8090/kom_login_new/KomLogin";
	
	public static int channel=0;
	
	public static boolean debug = false; 
	public static boolean androidTest = false;
	
	private static final String TAG = "kom";
	
	Button btnLogin = null;
	Button btnPay = null;
	Button btnTestPermission = null;
	Button btnLogout = null;
	Button btnEnterGameCenter = null;
	
	public Context mContext = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mContext = this;
		
		 //初始化登录信息
		initSDKInfo();
		
		if(debug&&androidTest){
			final LinearLayout layout=new LinearLayout(this);  
	        layout.setOrientation(LinearLayout.VERTICAL); 
	        
	        btnLogin  = new Button(this);
	        btnLogin.setText("登录");
	        btnLogin.setOnClickListener(this);
	        
	        btnPay  = new Button(this);
	        btnPay.setText("支付");
	        btnPay.setOnClickListener(this);
		        
	        btnTestPermission = new Button(this);
	        btnTestPermission.setText("获取手机信息(测试权限)");
	        btnTestPermission.setOnClickListener(this);
	        
	        btnEnterGameCenter = new Button(this);
	        btnEnterGameCenter.setText("进入应用中心");
	        btnEnterGameCenter.setOnClickListener(this);
	        
	        btnLogout = new Button(this);
	        btnLogout.setText("注销");
	        btnLogout.setOnClickListener(this);
	        
	        
	        
	        
	        
	        layout.addView(btnLogin);
	        layout.addView(btnPay);
	        layout.addView(btnTestPermission);
	        layout.addView(btnEnterGameCenter);
	        layout.addView(btnLogout);
	        
	        this.setContentView(layout);
		}
		
	}
	
	/**
	 * 初始化sdk信息 
	 * channel
	 * debug
	 * androidTest
	 */
	protected abstract void initSDKInfo();
	
	 /**
     * 获取手机信息
     */
	public void getPhoneInfo(){
    	String info = PhoneInfoUtil.getPhoneInfo(this);
    	if(androidTest){
    		toastMessage("phoneInfo:"+info);
    	}else{
    		UnitySendMessage("InitPanel", "OnResponseGetPhoneInfo", info);
    	}
    	
    }
    
	/**
	 * 调用unity
	 * @param objName
	 * @param methodName
	 * @param message
	 */
	public void UnitySendMessage(String objName,String methodName,String message){
    	if(!androidTest){
    		UnityPlayer.UnitySendMessage(objName, methodName,message);
    	}
    }
    
    /**
     * 调用unity 登录成功
     * @param message
     */
    public void sendLoginSuccessMessage(String message){
    	UnitySendMessage("InitPanel", "OnSdkLoginSuccess", message);
    }
    
    /**
     * 调用unity 登录失败
     * @param message
     */
    public void sendLoginFailedMessage(String message){
    	UnitySendMessage("InitPanel", "OnSdkLoginFail", message);
    }
    
    /**
     * 调用unity 取消登录
     */
    public void sendLoginCancelMessage(){
    	UnitySendMessage("InitPanel", "OnSdkLoginCancel", "取消登录");
    }
	
    /**
     * 提示信息
     * @param message
     */
    public void toastMessage(String message){
    	Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
    }
    
    public void logInfo(String message){
    	Log.i(TAG, message);
    }
	
    public Activity getCurrentUnityActivity(){
    	if(androidTest){
    		return AbstractUnityActivity.this;
    	}else{
    		return UnityPlayer.currentActivity;
    	}
    	
    }
    
    /**
     * 显示 提示框
     */
    private ProgressDialog progressDialog;
	public void showLoading(){
		showLoading("请稍候..");
	}
	public void showLoading(final String tips){
		Log.i("kom","显示progressDialog  "+tips);
    	new Handler(Looper.getMainLooper()).post(new Runnable(){
			@Override
			public void run(){
				if(progressDialog!=null){
					if(progressDialog.isShowing()){
						progressDialog.cancel();
					}
				}
				progressDialog = new ProgressDialog(AbstractUnityActivity.this);
				progressDialog.setMessage(tips);
				progressDialog.setIndeterminate(true);
				progressDialog.setCancelable(false);
				progressDialog.show();
			}
		});
	}
	public void hideLoading(){ 
		if(progressDialog != null){
			Log.i("kom","关闭progressDialog");
			progressDialog.setCancelable(true);
			progressDialog.cancel();
			progressDialog = null;
		} 
	}
    
	/**
	 * 登录方法
	 */
    public abstract void login();
    /**
     * 支付方法
     * @param userId
     * @param roleId
     * @param serverId
     * @param money
     * @param roleName
     */
    public abstract void pay(final int userId,final int roleId,final int serverId,final int money,final String roleName);
    
    /**
     * 登出
     */
    public void logout(){
    	
    }
    
    public void exitGame(){}
    
    /**
     * 进入应用中心
     */
    public void enterGameCenter(){
    	
    }
    
    
    public void createOrderAndPay(final int userId,final int roleId,final int serverId,final int money,final String roleName){
    	createOrderAndPay(userId,roleId,serverId,money,roleName,null);
    }
    /**
     * 先创建订单后充值的用此方法
     * @param userId
     * @param roleId
     * @param serverId
     * @param money
     */
    public void createOrderAndPay(final int userId,final int roleId,final int serverId,final int money,final String roleName,final CreateOrderSuccessCallBack callBack){
		//先生成充值记录
		//再调用充值
		StringBuilder params = new StringBuilder();
		params.append("?userId="+userId);
		params.append("&roleId="+roleId);
		params.append("&serverId="+serverId);
		params.append("&amount="+money);
		params.append("&channel="+channel);
		logInfo("充值平台:"+channel);
		String sign = Util.getMD5Str(userId+","+roleId+","+serverId+","+money+","+key);
		params.append("&sign="+sign);
		final String sparams = params.toString();
		new Handler(Looper.getMainLooper()).post(new Runnable(){
    		@Override
    		public void run(){
    			final Handler hd = new Handler(){
    				@Override
    				public void handleMessage(Message msg) {
    					hideLoading();
    					boolean result = msg.getData().getBoolean("result");
    					if(result){
    						int orderId = msg.getData().getInt("gameUserId");
    						//创建订单完成回调
    						if(callBack==null){
    							oncreateOrderSuccess(orderId,userId, roleId, serverId, money, roleName);
    						}else{
    							callBack.oncreateOrderSuccess(orderId,userId, roleId, serverId, money, roleName);
    						}
    					}else{
    						Toast.makeText(AbstractUnityActivity.this, "创建订单失败",Toast.LENGTH_SHORT).show();
    					}
    				}
    			};
    			showLoading("正在创建订单..");
    			//Toast.makeText(AbstractUnityActivity.this, "正在创建订单",Toast.LENGTH_SHORT).show();
    			new Thread(){
    				public void run() {
    					String result  = null;
    					Message msg = new Message();
						Bundle data = new Bundle();
    					try {
    						String url = debug?createOrderUrlDebug:createOrderUrl;
    						logInfo(url);
    						result = Util.getWebCon(url+sparams);	
    						if(result.startsWith("success:")){
    							String gameUserId = result.replace("success:", "");
    							
    							data.putBoolean("result", true);
    							data.putInt("gameUserId",Integer.parseInt(gameUserId));
    							msg.setData(data);
    							hd.sendMessage(msg);
    						}else{
    							data.putBoolean("result", false);
    							hd.sendMessage(msg);
    						}
    					} catch (Exception e) {
    						data.putBoolean("result", false);
							hd.sendMessage(msg);
    					}
    				};
    			}.start();
    		}
    	});
    }
    
    @Override
    public void oncreateOrderSuccess(int orderId,int userId,int roleId,int serverId,int money,String roleName){
    	
    }
   
    @Override
	public void onClick(View v) {
		if(v==btnLogin){
			login();
		}else if(v==btnPay){
			pay(1,1,1,1,"test");
		}else if(v==btnTestPermission){
			getPhoneInfo();
		}else if(v==btnLogout){
			logout();
		}else{
			enterGameCenter();
		}
	}
    
   	/**
	 * 进行网络检查
	 */
	public boolean checkNetwork() {
		// !!!在调用SDK初始化前进行网络检查
		// 当前没有拥有网络
		if (false == APNUtil.isNetworkAvailable(this)) {
			AlertDialog.Builder ab = new AlertDialog.Builder(this);
			ab.setMessage("网络未连接,请设置网络");
			ab.setPositiveButton("设置", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent("android.settings.SETTINGS");
					startActivityForResult(intent, 0);
				}
			});
			ab.setNegativeButton("退出", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					System.exit(0);
				}
			});
			ab.show();
			return false;
		} else {
			return true;
		}
	}
}
